<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 陈风任 <491085389@qq.com>
 * Date: 2021-12-17
 */

namespace weapp\DealerPlugin\logic;

use think\Db;
use Grafika\Color;
use Grafika\Grafika;
require_once ROOT_PATH . 'vendor/grafika/src/autoloader.php';

/**
 * 分销商公共逻辑定义
 * Class CatsLogic
 * @package common\Logic
 */
class DealerCommonLogic
{
    /**
     * 析构函数
     */
    function  __construct($appletsApi = '')
    {
        // 是否默认，0否，1是
        $this->default = 0;
        // 是否ajax调用
        $this->ajaxGet = 0;
        // 分销商会员ID
        $this->usersID = 0;
        // 分销商ID
        $this->dealerID = 0;
        // 海报生成文件夹目录路径
        $this->posterPath = '';
        // 海报生成设置
        $this->posterSet = [];
        // 小程序来源
        $this->appletsApi = $appletsApi;
        // 会员数据表
        $this->usersDb = Db::name('users');
        // 分销商数据信息表
        $this->dealerDb = Db::name('weapp_dealer');
        // 订单数据表
        $this->shopOrderDb = Db::name('shop_order');
        // 分销商数据信息表
        $this->dealerMoneyLogDb = Db::name('weapp_dealer_money_log');
    }

    // 获取分销商推广二维码海报
    public function getDealerPoster($usersID = 0, $dealerID = 0, $posterSet = [], $param = [])
    {
        if (empty($usersID) || empty($dealerID)) {
            return [
                'status' => false,
                'msg' => '分销商异常，推广海报生成失败',
            ];
        }

        // 分销商会员ID
        $this->usersID = $usersID;

        // 分销商ID
        $this->dealerID = $dealerID;

        // 海报生成文件夹目录路径
        $this->posterPath = UPLOAD_PATH . 'tmp/poster_' . $this->usersID . '_' . $this->dealerID . '/';

        // 默认海报生成设置
        $this->posterSet = !empty($posterSet) ? $posterSet : $this->getDefaultDealerSetting('poster');

        // 背景图片
        $posterImage = $this->posterSet['background'];

        // 分销商头像处理
        $dealerAvatar = $this->getDealerAvatar();
        
        // uni编辑的H5端标识
        $provider = input('param.provider/s', '');
        $provider = strtolower($provider);
        // 终端处理，H5终端则执行生成普通连接二维码
        if (!empty($param['terminal']) && 'h5' == $param['terminal']) {
            $appletsQrcode = $this->getMobileTerminalQrcode();
        }
        else if (!empty($provider) && 'h5' == $provider) {
            $appletsQrcode = $this->getH5MobileTerminalQrcode();
        }
        else {
            // 分销商小程序二维码处理
            $appletsQrcode = $this->getAppletsQrcode();
            if (empty($appletsQrcode['status'])) return $appletsQrcode;
        }

        // 组合并返回分销商海报图片
        return $this->getDealerPosterImage($posterImage, $dealerAvatar, $appletsQrcode['qrcode'], $param);
    }

    // 分销商头像下载到本地
    private function getDealerAvatar()
    {
        // 查询分销商头像URL
        $where = [
            'is_dealer' => 1,
            'users_id' => $this->usersID
        ];
        $dealerAvatar = $this->usersDb->where($where)->getField('head_pic');
        $dealerAvatar = get_default_pic($dealerAvatar, true);

        // 保存图片到临时图片夹并返回URL
        return $this->saveTmpImage($dealerAvatar, 'avatar');
    }

    // 网络图片下载到本地图片夹
    private function saveTmpImage($image = '', $imageName = '')
    {
        // 保存图片的完整路径
        $imageSavePath = $this->posterPath . $imageName . '_' . md5($this->usersID . $this->dealerID) . '.png';

        // 若文件夹不存在则创建
        !is_dir($this->posterPath) && tp_mkdir($this->posterPath);

        // 若图片存在则返回
        if (file_exists($imageSavePath)) return $imageSavePath;

        // 图片保存到文件处理
        $ch = curl_init($image);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
        $img = curl_exec($ch);
        curl_close($ch);
        $fp = fopen($imageSavePath, 'w');
        fwrite($fp, $img);
        fclose($fp);

        // 返回图片本地路径
        return $imageSavePath;
    }

    // 获取分销商公众号二维码
    private function getMobileTerminalQrcode()
    {
        // 保存图片的完整路径
        $qrCodeSavePath = 'qrcode_' . md5($this->usersID . $this->dealerID) . '_h5.png';
        if (!empty($this->ajaxGet)) {
            $qrCodeSavePath = 'qrcode_' . md5($this->ajaxGet) . '_h5.png';
        } else if (!empty($this->default)) {
            $qrCodeSavePath = 'qrcode.png';
        }
        $qrCodeSavePath = $this->posterPath . $qrCodeSavePath;
        // 二维码URL
        $dealerParam = base64_encode(json_encode($this->usersID . '_eyoucms_' . $this->dealerID));
        $qrCodeSaveUrl = request()->domain() . ROOT_DIR . '/index.php?m=user&c=Users&a=index&dealerParam=' . $dealerParam;
        // 生成二维码
        vendor('wechatpay.phpqrcode.phpqrcode');
        $qrcode = new \QRcode;
        $qrcode->png($qrCodeSaveUrl, $qrCodeSavePath);
        return [
            'status' => true,
            'qrcode' => $qrCodeSavePath,
        ];
    }

    // 获取分销商H5公众号二维码(uni代码生成的H5端)
    private function getH5MobileTerminalQrcode()
    {
        // 保存图片的完整路径
        $qrCodeSavePath = 'qrcode_' . md5($this->usersID . $this->dealerID) . '_uni_h5.png';
        if (!empty($this->ajaxGet)) {
            $qrCodeSavePath = 'qrcode_' . md5($this->ajaxGet) . '_uni_h5.png';
        } else if (!empty($this->default)) {
            $qrCodeSavePath = 'qrcode.png';
        }
        $qrCodeSavePath = $this->posterPath . $qrCodeSavePath;
        // 二维码URL
        // $qrCodeSaveUrl = request()->domain() . ROOT_DIR . '/h5/#/pages/index?index=1';
        $qrCodeSaveUrl = request()->domain() . ROOT_DIR . '/h5/#/pages/index?index=1&scene=' . $this->usersID . '_eyoucms_' . $this->dealerID;
        // dump($qrCodeSaveUrl);exit;
        // 生成二维码
        vendor('wechatpay.phpqrcode.phpqrcode');
        $qrcode = new \QRcode;
        $qrcode->png($qrCodeSaveUrl, $qrCodeSavePath);
        return [
            'status' => true,
            'qrcode' => $qrCodeSavePath,
        ];
    }

    // 获取分销商小程序二维码
    private function getAppletsQrcode()
    {
        // 保存图片的完整路径
        $qrCodeSavePath = 'qrcode_' . md5($this->usersID . $this->dealerID) . '.png';
        if (!empty($this->ajaxGet)) {
            $qrCodeSavePath = 'qrcode_' . md5($this->ajaxGet) . '.png';
        } else if (!empty($this->default)) {
            $qrCodeSavePath = 'qrcode.png';
        }
        $qrCodeSavePath = $this->posterPath . $qrCodeSavePath;

        // 若文件夹不存在则创建
        if (empty($this->default) && !is_dir($this->posterPath)) tp_mkdir($this->posterPath);

        // 若图片存在则返回
        if (file_exists($qrCodeSavePath)) {
            return [
                'status' => true,
                'qrcode' => $qrCodeSavePath,
            ];
        }

        // 是否配置小程序信息
        $appletsToken = get_weixin_access_token(true, $this->appletsApi);
        if (empty($appletsToken['code'])) {
            return [
                'status' => false,
                'msg' => $appletsToken['msg'],
            ];
        }

        // 调用微信接口获取小程序二维码
        return $this->getWeChatAppletsQrcode($appletsToken['access_token'], $qrCodeSavePath);
    }

    // 获取微信小程序分销商二维码
    private function getWeChatAppletsQrcode($accessToken = null, $qrCodeSavePath = null)
    {
        // 获取微信小程序二维码
        $postUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $accessToken;
        // $page = !empty($this->default) || !empty($this->ajaxGet) ? 'pages/index/index' : 'pages/dealer/apply/apply';
        $page = 'pages/user/index';
        $scene = $this->usersID . '_eyoucms_' . $this->dealerID;
        $width = '430';
        $postData = compact('page', 'scene', 'width');
        $appletsQrcode = httpRequest($postUrl, 'POST', json_encode($postData, JSON_UNESCAPED_UNICODE));

        // 保存图片，保存成功则返回图片路径
        $qrCodeSavePath = ltrim($qrCodeSavePath, "/");
        if (@file_put_contents($qrCodeSavePath, $appletsQrcode)) {
            $result = [
                'status' => true,
                'qrcode' => $qrCodeSavePath,
            ];
        } else {
            $result = [
                'status' => false,
                'prompt' => '获取二维码失败，请重试',
            ];
        }

        return $result;
    }

    // 获取分销商海报图
    private function getDealerPosterImage($posterImage = null, $dealerAvatar = null, $appletsQrcode = null, $param = [])
    {
        $Grafika = new Grafika;
        $editor = $Grafika::createEditor(['Gd']);
        // 打开海报背景图
        $editor->open($backdropImage, $posterImage);

        // 生成圆形用户头像
        $this->CircularImage($dealerAvatar, $dealerAvatar);
        // 打开用户头像
        $editor->open($avatarImage, $dealerAvatar);
        // 重设用户头像宽高
        $avatarWidth = $this->posterSet['avatar']['width'] * 2;
        $editor->resizeExact($avatarImage, $avatarWidth, $avatarWidth);
        // 用户头像添加到背景图
        $avatarX = $this->posterSet['avatar']['left'] * 2;
        $avatarY = $this->posterSet['avatar']['top'] * 2;
        $editor->blend($backdropImage, $avatarImage, 'normal', 1.0, 'top-left', $avatarX, $avatarY);

        if (empty($param['terminal']) || 'h5' != $param['terminal']) {
            $provider = input('param.provider/s', '');
            if (empty($provider) || 'h5' != $provider) {
                // 生成圆形小程序码
                $this->CircularImage($appletsQrcode, $appletsQrcode);
            }
        }
        // 打开小程序码
        $editor->open($qrcodeImage, $appletsQrcode);
        // 重设小程序码宽高
        $qrcodeWidth = $this->posterSet['qrcode']['width'] * 2;
        $editor->resizeExact($qrcodeImage, $qrcodeWidth, $qrcodeWidth);
        // 小程序码添加到背景图
        $qrcodeX = $this->posterSet['qrcode']['left'] * 2;
        $qrcodeY = $this->posterSet['qrcode']['top'] * 2;
        $editor->blend($backdropImage, $qrcodeImage, 'normal', 1.0, 'top-left', $qrcodeX, $qrcodeY);

        // 写入用户昵称
        $nickName = '会员昵称';
        if (empty($this->ajaxGet) && empty($this->default)) {
            $where = [
                'is_dealer' => 1,
                'users_id' => $this->usersID
            ];
            $nickName = $this->usersDb->where($where)->getField('nickname');
        }

        // 获取指定长度的字符串
        $result = $this->GetSpecifiedLengthString($nickName, '5.5');
        $nickName = $result['resultStr'];
        
        // 处理昵称左右位置
        $posterSetNickNameLeft = $this->posterSet['nickname']['left'];
        if ($result['n'] <= 1) {
            $posterSetNickNameLeft += 35;
        } else if ($result['n'] <= 2) {
            $posterSetNickNameLeft += 30;
        } else if ($result['n'] <= 3) {
            $posterSetNickNameLeft += 22;
        } else if ($result['n'] <= 4) {
            $posterSetNickNameLeft += 13;
        } else if ($result['n'] <= 5) {
            $posterSetNickNameLeft += 5;
        }

        $fontSize = $this->posterSet['nickname']['size'] * 2 * 0.76;
        $fontX = $posterSetNickNameLeft * 2;
        $fontY = $this->posterSet['nickname']['top'] * 2;
        $fontPath = $Grafika::fontsDir() . DS . 'st-heiti-light.ttc';
        $editor->text($backdropImage, $nickName, $fontSize, $fontX, $fontY, new Color($this->posterSet['nickname']['color']), $fontPath);

        // 保存图片
        $posterImagePath = 'poster_' . md5($this->usersID . $this->dealerID) . '.png';
        if (!empty($this->ajaxGet)) {
            $posterImagePath = 'poster_' . md5($this->ajaxGet) . '.png';
        } else if (!empty($this->default)) {
            $posterImagePath = 'default-poster.png';
        }
        $posterImagePath = ltrim($this->posterPath, "/") . $posterImagePath;
        $editor->save($backdropImage, $posterImagePath);

        // 返回分销商海报
        if (!empty($this->default)) {
            return $posterImagePath;
        } else {
            return request()->domain() . ROOT_DIR . '/' . $posterImagePath;
        }
    }

    // 生成圆形用户头像
    private function CircularImage($ImagePath = '', $SaveName = '')
    {
        $srcImg = imagecreatefromstring(file_get_contents($ImagePath));
        $w = imagesx($srcImg);
        $h = imagesy($srcImg);
        $w = $h = min($w, $h);
        $newImg = imagecreatetruecolor($w, $h);

        // 这一句一定要有
        imagesavealpha($newImg, true);

        // 拾取一个完全透明的颜色,最后一个参数127为全透明
        $bg = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
        imagefill($newImg, 0, 0, $bg);
        $r = $w / 2; //圆半径
        for ($x = 0; $x < $w; $x++) {
            for ($y = 0; $y < $h; $y++) {
                $rgbColor = imagecolorat($srcImg, $x, $y);
                if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r))) {
                    imagesetpixel($newImg, $x, $y, $rgbColor);
                }
            }
        }

        // 输出图片到文件
        imagepng($newImg, $SaveName);

        // 释放空间
        imagedestroy($srcImg);
        imagedestroy($newImg);
    }

    // 获取指定长度的字符串(字符混和)
    private function GetSpecifiedLengthString($paramStr = '', $paramLength = 0)
    {
        $i = $n = 0;
        $resultStr = '';
        $strLength = strlen ( $paramStr ); // 字符串的字节数
        while ( ($n < $paramLength) and ($i <= $strLength) ) {
            $temp_str = substr ( $paramStr, $i, 1 );
            $ascnum = Ord ( $temp_str ); // 得到字符串中第$i位字符的ascii码 
            if ($ascnum >= 224) {
                // 如果ASCII位高与224
                $resultStr = $resultStr . substr ( $paramStr, $i, 3 );
                $i = $i + 3; // 实际Byte计为3
                $n ++; // 字串长度计1
            } else if ($ascnum >= 192) {
                // 如果ASCII位高与192
                $resultStr = $resultStr . substr ( $paramStr, $i, 2 );
                $i = $i + 2; // 实际Byte计为2
                $n ++; // 字串长度计1
            } else if ($ascnum >= 65 && $ascnum <= 90) {
                // 如果是大写字母
                $resultStr = $resultStr . substr ( $paramStr, $i, 1 );
                $i = $i + 1; // 实际的Byte数仍计1个
                $n ++; // 但考虑整体美观，大写字母计成一个高位字符
            } else {
                // 其他情况下，包括小写字母和半角标点符号
                $resultStr = $resultStr . substr ( $paramStr, $i, 1 );
                $i = $i + 1; // 实际的Byte数计1个
                $n = $n + 0.5; // 小写字母和半角标点等与半个高位字符宽...
            }
        }

        // 超过长度时在尾处加上省略号
        $resLength = strlen ( $resultStr );
        if ($strLength > $paramLength && $strLength > $resLength) $resultStr = $resultStr . "...";

        // 返回指定长度字符串
        $result = [
            'n' => $n,
            'strLength' => $strLength,
            'resLength' => $resLength,
            'resultStr' => $resultStr,
        ];
        return $result;
    }

    // 默认分销设置
    public function getDefaultDealerSetting($field = '')
    {
        // 组装默认设置
        $DefaultSetting =  [
            'dealer' => [
                'basic' => [
                    'open' => 0,
                    'level' => 1,
                    'self_buy' => 1
                ],
                'condition' => [
                    'review' => 0,
                    // 'specify_buy' => 0,
                    'down_level' => 1
                ],
                'rebate' => [
                    'first_rate' => 0,
                    'second_rate' => 0,
                    'third_rate' => 0
                ],
                'settle' => [
                    'min_withdraw' => 0,
                    'rebate_days' => 7
                ],
                'center' => [
                    'title' => '分销中心',
                    'prompt' => '您还不是分销商，请先提交申请。',
                    'submit' => '立即加入',
                    'referrer' => '推荐人',
                    'available' => '可提现',
                    'freeze' => '待提现',
                    'grand_total' => '已提现',
                    'withdraw' => '去提现'
                ],
                'apply' => [
                    'title' => '申请成为分销商',
                    'name' => '请填写申请信息',
                    'pact' => '分销商申请协议',
                    'submit' => '申请成为经销商',
                    'review_msg' => '您的申请已受理，正在进行信息核验，请耐心等待。',
                    'go_shop' => '去商城逛逛'
                ],
                'order' => [
                    'title' => '分销订单',
                    'all' => '全部',
                    'notsettle' => '未结算',
                    'settle' => '已结算'
                ],
                'myteam' => [
                    'title' => '我的团队',
                    'total' => '团队总人数',
                    'first' => '一级团队',
                    'second' => '二级团队',
                    'third' => '三级团队'
                ],
                'withdraw_list' => [
                    'title' => '提现明细',
                    'all' => '全部',
                    'review' => '审核中',
                    'passed' => '审核通过',
                    'withdraw' => '已打款',
                    'turn_down' => '驳回'
                ],
                'withdraw_apply' => [
                    'title' => '申请提现',
                    'available' => '可提现佣金',
                    'money' => '提现金额',
                    'placeholder' => '请输入要提取的金额',
                    'min_withdraw' => '最低提现佣金',
                    'submit' => '提交申请'
                ],
                'qrcode' => [
                    'title' => '推广二维码'
                ],
                'pact' => [
                    'pact_content' => '这里是申请分销商协议内容',
                ],
                'background' => [
                    'center' => ROOT_PATH . 'public/static/common/images/dealer-bg.png',
                    'apply' => ROOT_PATH . 'public/static/common/images/dealer-bg.png',
                    'withdraw' => ROOT_PATH . 'public/static/common/images/dealer-bg.png'
                ],
                'poster' => [
                    'background' => ROOT_PATH . 'weapp/DealerPlugin/template/skin/images/default-bg.png',
                    'avatar' => [
                        'top' => 24,
                        'left' => 152,
                        'width' => 70,
                        'style' => 1 // 1圆形，2正方形
                    ],
                    'nickname' => [
                        'top' => 110,
                        'left' => 152,
                        'size' => 14,
                        'color' => '#000000'
                    ],
                    'qrcode' => [
                        'top' => 135,
                        'left' => 138,
                        'width' => 100,
                        'style' => 1 // 1圆形，2正方形
                    ]
                ]
            ]
        ];

        // 返回默认设置
        if (!empty($field)) {
            return $DefaultSetting['dealer'][$field];
        } else {
            return $DefaultSetting;
        }
    }

    // 订单结算分佣的分销商信息处理
    public function dealerOrderHandle($orderData = [], $userInfo = [])
    {
        // 检测是否安装秒杀插件
        if (is_dir('./weapp/Seckill/')) {
            $seckillRow = model('Weapp')->getWeappList('Seckill');
            if (!empty($seckillRow) && 1 === intval($seckillRow['status'])) {
                if (!empty($orderData['is_seckill_order'])) {
                    $seckill_is_distribution = Db::name('weapp_seckill')->where('id',$orderData['is_seckill_order'])->value('is_distribution');
                    if (empty($seckill_is_distribution)) return $orderData;
                }
            }
        }

        $dealer_id = $dealer_order = $dealer_rebate = $dealer_users_id = $one_level_rebate = $two_level_rebate = $skipTwoLevel = 0;
        // 分销设置
        $dealer = getUsersConfigData('dealer');
        // 分销功能开启
        if (!empty($dealer['dealer_open'])) {
            // 一级分销模式
            if (!empty($dealer['dealer_level']) && 1 === intval($dealer['dealer_level'])) {
                $skipTwoLevel = 1;
                // 当前会员是 分销商 且 没有上级分销商 则执行 (一级分销商下单)
                if (!empty($userInfo['is_dealer']) && empty($userInfo['parent_users_id']) && empty($userInfo['parent_dealer_id'])) {
                    $dealer_order = 1;
                    $dealer_users_id = empty($dealer['dealer_self_buy']) ? 0 : $userInfo['users_id'];
                    $dealer_id = empty($dealer['dealer_self_buy']) ? 0 : $this->getDealerID($userInfo['users_id']);
                }
                // 当前会员非 分销商 且 存在上级分销商 则执行 (分销商客户下单)
                else if (empty($userInfo['is_dealer']) && !empty($userInfo['parent_users_id']) && !empty($userInfo['parent_dealer_id'])) {
                    // 判断当前会员的上级是一级分销商还是二级分销商，二级分销商在一级分销模式下暂时失效，所下订单均为非分销订单
                    // 当前会员只有上级分销商没有顶级分销商则表示会员为一级分销商的客户，没有二级分销佣金
                    if (empty($userInfo['top_users_id']) && empty($userInfo['top_dealer_id'])) {
                        $dealer_order = 1;
                        $dealer_id = $userInfo['parent_dealer_id'];
                        $dealer_users_id = $userInfo['parent_users_id'];
                    }
                }
            }
            // 二级分销模式
            else if (!empty($dealer['dealer_level']) && 2 === intval($dealer['dealer_level'])) {
                // 当前会员是 分销商 则执行 (分销商下单)
                if (!empty($userInfo['is_dealer'])) {
                    $dealer_order = 1;
                    $dealer_users_id = empty($dealer['dealer_self_buy']) ? $userInfo['parent_users_id'] : $userInfo['users_id'];
                    $dealer_id = empty($dealer['dealer_self_buy']) ? $userInfo['parent_dealer_id'] : $this->getDealerID($userInfo['users_id']);
                    // 是否不给二级分销商进行佣金结算
                    if (empty($dealer['dealer_self_buy']) || (empty($userInfo['parent_users_id']) && empty($userInfo['parent_dealer_id']))) {
                        $skipTwoLevel = 1;
                    }
                }
                // 当前会员非 分销商 且 存在上级分销商 则执行 (分销商客户下单)
                else if (empty($userInfo['is_dealer']) && !empty($userInfo['parent_users_id']) && !empty($userInfo['parent_dealer_id'])) {
                    $dealer_order = 1;
                    $dealer_id = $userInfo['parent_dealer_id'];
                    $dealer_users_id = $userInfo['parent_users_id'];
                    // 当前会员只有上级分销商没有顶级分销商则表示会员为一级分销商的客户，没有二级分销佣金
                    if (empty($userInfo['top_users_id']) && empty($userInfo['top_dealer_id'])) $skipTwoLevel = 1;
                }
            }

            // 订单结算分佣的分销比例处理
            if (!empty($dealer_id) && !empty($dealer_users_id)) {
                $dealer_rebate = intval($dealer['dealer_rebate']);
                $one_level_rebate = $dealer['dealer_one_level_rebate'];
                $two_level_rebate = !empty($skipTwoLevel) ? 0 : $dealer['dealer_two_level_rebate'];
            } else {
                $dealer_order = 0;
            }
        }

        $orderData['dealer_id'] = !empty($dealer_id) ? intval($dealer_id) : 0;
        $orderData['dealer_order'] = !empty($dealer_order) ? intval($dealer_order) : 0;
        $orderData['dealer_rebate'] = !empty($dealer_rebate) ? intval($dealer_rebate) : 0;
        $orderData['dealer_users_id'] = !empty($dealer_users_id) ? intval($dealer_users_id) : 0;
        $orderData['one_level_rebate'] = !empty($one_level_rebate) ? strval($one_level_rebate) : 0;
        $orderData['two_level_rebate'] = !empty($two_level_rebate) ? strval($two_level_rebate) : 0;
        // dump($orderData);exit;
        
        // 返回数据
        return $orderData;
    }

    // 查询 分销商的分销订单执行分销订单结算分佣处理
    public function dealerOrderSettlementHandle($users_id = 0, $usersConfig = [])
    {
        if (!empty($usersConfig['dealer_open']) && !empty($usersConfig['dealer_settlement'])) {
            // 如果 开启分销功能 则执行
            if (2 === intval($usersConfig['dealer_settlement']) && !empty($usersConfig['dealer_settlement_day'])) {
                // 计算分销订单结算佣金的时间
                $dealerSettlementDay = intval($usersConfig['dealer_settlement_day']) * 86400;
                $time = getTime() - intval($dealerSettlementDay);

                // 查询分销商所有下级会员ID
                $users_ids = $this->getDealerAllSubLevelUsersID($users_id);

                // 查询订单
                $where = [
                    'order_status' => 3,
                    'dealer_order' => 1,
                    'handle_rebate' => 0,
                    'dealer_id' => ['>', 0],
                    'dealer_users_id' => ['>', 0],
                    'confirm_time' => ['<', $time],
                    'users_id' => ['IN', $users_ids],
                ];
                $shopOrder = Db::name('shop_order')->where($where)->select();
                if (!empty($shopOrder)) {
                    // 订单结算佣金执行
                    foreach ($shopOrder as $value) {
                       $this->dealerOrderSettlementExecute($value['order_id'], $value['users_id'], 'auto', $usersConfig);
                    }
                }
            }
        }
    }

    // 订单结算佣金执行
    public function dealerOrderSettlementExecute($order_id = 0, $users_id = 0, $action = 'confirm', $dealer = [])
    {
        // 分销设置
        $dealer = !empty($dealer) ? $dealer : getUsersConfigData('dealer');
        // 分销商佣金结算 如果是 订单完成立即结算 则执行
        if ('confirm' == $action && !empty($dealer['dealer_settlement']) && 1 !== intval($dealer['dealer_settlement'])) {
            return false;
        }
        // 分销商佣金结算 如果是 自定义结算天数 则执行
        else if ('auto' == $action && !empty($dealer['dealer_settlement']) && 2 !== intval($dealer['dealer_settlement'])) {
            return false;
        }

        // 如果 开启分销功能 且 分销商佣金结算是订单完成立即结算
        if (!empty($dealer['dealer_open'])) {
            $times = getTime();
            $where = [
                'order_id' => intval($order_id),
                'users_id' => intval($users_id),
            ];
            // 查询是否分销订单
            $shopOrder = $this->shopOrderDb->where($where)->find();

            // 如果 是分销订单 且 订单分销佣金未结算 则执行
            if (!empty($shopOrder['dealer_order']) && empty($shopOrder['handle_rebate'])) {
                $dealerTotalAmount = 0;
                // 使用 订单商品合计总额 进行计算分佣
                if (!empty($shopOrder['dealer_rebate']) && 1 === intval($shopOrder['dealer_rebate'])) {
                    $dealerTotalAmount = unifyPriceHandle($shopOrder['order_total_amount']);
                }
                // 使用 订单实际支付总额(余额抵扣+实付款) 进行计算分佣
                else if (!empty($shopOrder['dealer_rebate']) && 2 === intval($shopOrder['dealer_rebate'])) {
                    $dealerTotalAmount = unifyPriceHandle($shopOrder['order_amount']);
                    // 存在运费则扣除运费，运费不在分销佣金计算中
                    if (!empty($shopOrder['shipping_fee'])) {
                        $dealerTotalAmount = unifyPriceHandle(floatval($dealerTotalAmount) - floatval($shopOrder['shipping_fee']));
                    }
                }

                // 如果 订单存在分销商ID 和 分销商会员ID 则执行
                if (!empty($dealerTotalAmount) && !empty($shopOrder['dealer_id']) && !empty($shopOrder['dealer_users_id'])) {
                    // 订单分佣处理
                    if (!empty($shopOrder['one_level_rebate'])) {
                        // 查询 分销商是否存在 且 分销商状态正常
                        $where = [
                            'dealer_status' => 1,
                            'system_dealer' => 0,
                            'dealer_id' => intval($shopOrder['dealer_id']),
                            'users_id' => intval($shopOrder['dealer_users_id']),
                        ];
                        $oneDealer = $this->dealerDb->where($where)->find();
                        // 分销商正常，进行分佣操作
                        if (!empty($oneDealer)) {
                            // 计算一级返佣比例
                            $oneLevelRebate = intval($shopOrder['one_level_rebate']) / 100;
                            $oneLevelRebate = unifyPriceHandle(floatval($oneLevelRebate) * floatval($dealerTotalAmount));
                            // 进行一级分佣
                            $where = [
                                'system_dealer' => 0,
                                'dealer_status' => 1,
                                'users_id' => intval($oneDealer['users_id']),
                                'dealer_id' => intval($oneDealer['dealer_id']),
                            ];
                            $update = [
                                'update_time' => $times,
                                'dealer_money' => Db::raw('dealer_money+' . ($oneLevelRebate)),
                            ];
                            $this->dealerDb->where($where)->update($update);

                            // 分销商可用金额操作记录
                            $this->dealerMoneyLog($shopOrder, $oneDealer, $oneLevelRebate);
                        }
                    }
                    if (!empty($oneDealer) && !empty($shopOrder['two_level_rebate'])) {
                        $twoDealer = $this->getDealerParentInfo($oneDealer['users_id']);
                        // 存在上级分销商
                        if (!empty($twoDealer)) {
                            // 计算二级返佣比例
                            $twoLevelRebate = intval($shopOrder['two_level_rebate']) / 100;
                            $twoLevelRebate = unifyPriceHandle(floatval($twoLevelRebate) * floatval($dealerTotalAmount));
                            // 进行一级分佣
                            $where = [
                                'system_dealer' => 0,
                                'dealer_status' => 1,
                                'users_id' => intval($twoDealer['users_id']),
                                'dealer_id' => intval($twoDealer['dealer_id']),
                            ];
                            $update = [
                                'update_time' => $times,
                                'dealer_money' => Db::raw('dealer_money+' . ($twoLevelRebate)),
                            ];
                            $this->dealerDb->where($where)->update($update);

                            // 分销商可用金额操作记录
                            $this->dealerMoneyLog($shopOrder, $twoDealer, $twoLevelRebate);
                        }
                    }

                    // 更新订单为已结算分佣
                    $where = [
                        'order_id' => intval($shopOrder['order_id']),
                        'users_id' => intval($shopOrder['users_id']),
                    ];
                    $update = [
                        'handle_rebate' => 1,
                        'update_time' => $times,
                    ];
                    $this->shopOrderDb->where($where)->update($update);
                }
            }
        }
    }

    // 分销商可用金额操作记录
    public function dealerMoneyLog($param = [], $dealer = [], $logActionMoney = 0, $logType = 0)
    {
        // 判断是 订单分佣 还是 提现余额
        if (!empty($param['order_id'])) {
            $logType = 1;
            $logShow = 1;
            $logNote = '分销订单结算分佣到佣金';
            $logAfterMoney = unifyPriceHandle(floatval($dealer['dealer_money']) + floatval($logActionMoney));
        } else if (!empty($param['withdraw_id'])) {
            // 拒绝提现申请记录
            if (3 === intval($logType)) {
                $logType = 3;
                $logShow = 1;
                $logNote = '提现申请被拒绝，恢复提现金额到佣金';
                $logAfterMoney = unifyPriceHandle(floatval($dealer['dealer_money']) + floatval($logActionMoney));
            }
            // 删除提现申请记录
            else if (4 === intval($logType)) {
                $logType = 4;
                $logShow = 1;
                $logNote = '提现申请被删除，恢复提现金额到佣金';
                $logAfterMoney = unifyPriceHandle(floatval($dealer['dealer_money']) + floatval($logActionMoney));
            }
            // 添加提现申请记录
            else {
                $logType = 2;
                $logShow = 1;
                $logNote = '分销商提现佣金到余额';
                $logAfterMoney = unifyPriceHandle(floatval($dealer['dealer_money']) - floatval($logActionMoney));
            }
        }

        // 添加操作记录
        $times = getTime();
        $insert = [
            'order_id' => !empty($param['order_id']) ? intval($param['order_id']) : 0,
            'users_id' => !empty($dealer['users_id']) ? intval($dealer['users_id']) : 0,
            'dealer_id' => !empty($dealer['dealer_id']) ? intval($dealer['dealer_id']) : 0,
            'withdraw_id' => !empty($param['withdraw_id']) ? intval($param['withdraw_id']) : 0,
            'log_type' => !empty($logType) ? intval($logType) : 1,
            'log_before_money' => !empty($dealer['dealer_money']) ? floatval($dealer['dealer_money']) : 0,
            'log_action_money' => !empty($logActionMoney) ? floatval($logActionMoney) : 0,
            'log_after_money' => !empty($logAfterMoney) ? floatval($logAfterMoney) : 0,
            'log_note' => !empty($logNote) ? strval($logNote) : '',
            'log_show' => !empty($logShow) ? intval($logShow) : 1,
            'add_time' => $times,
            'update_time' => $times,
        ];
        $this->dealerMoneyLogDb->insert($insert);
    }

    // 通过 users_id 查询 dealer_id
    private function getDealerID($users_id = 0)
    {
        $where = [
            'system_dealer' => 0,
            'dealer_status' => 1,
            'users_id' => $users_id,
        ];
        return $this->dealerDb->where($where)->getField('dealer_id');
    }

    // 通过 users_id 查询 分销商所有下级会员ID
    private function getDealerAllSubLevelUsersID($users_id = 0)
    {
        return $this->usersDb->where('users_id|parent_users_id|top_users_id', $users_id)->column('users_id');
    }

    // 通过 users_id 查询 上级分销商信息
    private function getDealerParentInfo($users_id = 0)
    {
        $where = [
            'b.is_dealer' => 1,
            'a.system_dealer' => 0,
            'a.dealer_status' => 1,
            'b.users_id' => $users_id,
        ];
        return $this->dealerDb->alias('a')->field('a.*')->where($where)->join('__USERS__ b', 'a.users_id = b.parent_users_id', 'LEFT')->find();
    }

    // 删除会员时同步删除分销商，如果是一级分销商则将下级分销商和下级客户归属到系统分销商
    public function dealerSynchronizeDelete($users_ids = [])
    {
        // 查询会员是否有分销商数据
        $where = [
            'users_id' => ['IN', $users_ids]
        ];
        $dealer = Db::name('weapp_dealer')->where($where)->select();
        if (!empty($dealer)) {
            // 删除分销商数据
            Db::name('weapp_dealer')->where($where)->delete(true);
            Db::name('weapp_dealer_apply')->where($where)->delete(true);
            Db::name('weapp_dealer_money_log')->where($where)->delete(true);
            Db::name('weapp_dealer_withdraw')->where($where)->delete(true);

            // 分销商ID
            $dealer_ids = get_arr_column($dealer, 'dealer_id');

            // 将分销商涉及的订单变更为非分销订单
            $where = [
                'dealer_order' => 1,
                'handle_rebate' => 0,
                'dealer_id' => ['IN', $dealer_ids]
            ];
            $update = [
                'dealer_id' => 0,
                'dealer_users_id' => 0,
                'dealer_order' => 0,
                'dealer_rebate' => 0,
                'handle_rebate' => 0,
                'one_level_rebate' => 0,
                'two_level_rebate' => 0,
                'update_time' => getTime(),
            ];
            Db::name('shop_order')->where($where)->update($update);

            // 查询系统分销商信息
            $where = [
                'system_dealer' => 1,
                'users_id' => 99999999,
            ];
            $systemDealer = Db::name('weapp_dealer')->where($where)->find();

            // 更新分销商的下级分销商为系统分销商的下级分销商
            $where = [
                'parent_dealer_id' => ['IN', $dealer_ids]
            ];
            $update = [
                'parent_users_id' => $systemDealer['users_id'],
                'parent_dealer_id' => $systemDealer['dealer_id'],
                'update_time' => getTime(),
            ];
            Db::name('users')->where($where)->update($update);

            // 更新分销商的顶级客户为系统分销商的顶级客户
            $where = [
                'top_dealer_id' => ['IN', $dealer_ids]
            ];
            $update = [
                'top_users_id' => $systemDealer['users_id'],
                'top_dealer_id' => $systemDealer['dealer_id'],
                'update_time' => getTime(),
            ];
            Db::name('users')->where($where)->update($update);
        }
    }
}